import axios from 'axios';
import { message } from 'antd';
import { defaultPageSize, HOST }from '../config/default.js';
import { isLocalhost, cache } from "./common.js";

const responseStatusText = {
  400: '请求错误(400)',
  401: '未授权，请重新登录(401)',
  403: '拒绝访问(403)',
  404: '请求出错(404)',
  408: '请求超时(408)',
  500: '服务器错误(500)',
  501: '服务未实现(501)',
  502: '网络错误(502)',
  503: '服务不可用(503)',
  504: '网络超时(504)',
  505: 'HTTP版本不受支持(505)',
  'default': `连接出错!`
};

const instance = axios.create({
  //当创建实例的时候配置默认配置
  xsrfCookieName: 'xsrf-token'
});

instance.defaults.timeout = 100001;

//添加请求拦截器
instance.interceptors.request.use(function(config){
  if(config.url.indexOf('ByPage')!==-1) {
    if (config.params !== undefined) {
      config.params = {
        pageInfo: config.params.pageInfo ? config.params.pageInfo : {
          'page': 1,
          'rows': defaultPageSize
        },
        ...config.params,
      }
    } else if (config.data !== undefined) {
      config.data = {
        pageInfo: config.data.pageInfo ? config.data.pageInfo : {
          'page': 1,
          'rows': defaultPageSize
        },
        ...config.data,
      }
    }
  }
  if(config.url.indexOf('http')===-1){
    config.url = HOST + config.url;
  }

  return config;
}, (error) => {
  return Promise.reject(error);
});

//添加一个响应拦截器
instance.interceptors.response.use((response) => {
  // 1.成功
  if (response.status===200) {
    return response.data;
  }
  if (response.status===204) {
    return ;
  }
  // 3.其他失败，比如校验不通过等
  message.error(response.msg)

  return Promise.reject(response.data);
}, function (err) {
  if (err && err.response) {
    const { status = 'default', data } = err.response;
    err.message = responseStatusText[status];
    if(status === 401){
      cache.clear('Authorization');
      cache.clear('Right');
      cache.clear('_s');
      cache.clear('authHeader');
      return;
    }
    if(data){
      err.message = `${err.message}  ${data.msg}`;
    }
  }else{
    err.message = '连接服务器失败!'
  }

  return Promise.reject({
    message: err.message,
  });
});

// 建立唯一的key值
function buildUrl (url, params = {}) {
  const sortedParams = Object.keys(params).sort().reduce((result, key) => {
    result[key] = params[key]
    return result
  }, {})

  url += `?${JSON.stringify(sortedParams)}`
  return url
}

export function getHeader() {
  let authHeader=cache.get("authHeader")
  if(authHeader){
    return authHeader;
  }
  try {
    let auth = cache.get('Authorization');
    authHeader = {
      'Content-Type':'application/json;charset=UTF-8',
      'Cache-Control': 'no-cache',
      'Authorization': auth?(auth.accessToken?auth.accessToken:''):''
    }
  } catch (e) {
  }

  return authHeader;
}

export default {
  get(url, param={}, needCache=false, paramsInBody=false) {
    let res;
    if(needCache){
      res = cache.get(buildUrl(url,param));
    }
    if(res){
      return new Promise((resolve,reject) => {
        resolve(res);
      });
    }else{
      let config = {
        method: 'get',
        headers: getHeader(),
        url
      }
      if(paramsInBody) {
        config.data =  param;
      } else {
        config.params =  param;
      }

      return new Promise((resolve,reject) => {
        instance(config).then(res => {
          if(needCache){
            cache.set(buildUrl(url,param),res)
          }
          resolve(res)
        }).catch(err =>{
          message.error(err.message)
          reject(err)
        })
      })
    }
  },
  post(url, param={}) {
    return new Promise((resolve,reject) => {
      instance({
        method: 'post',
        headers: getHeader(),
        url,
        params: param,
      }).then(res => {
        resolve(res)
      }).catch(err =>{
        message.error(err.message)
        reject(err)
      })
    })
  },
  postJson(url, data={}) {
    return new Promise((resolve,reject) => {
      instance({
        method: 'post',
        headers: getHeader(),
        url,
        data: data,
      }).then(res => {
        resolve(res);
      }).catch(err =>{
        message.error(err.message);
        reject(err);
      })
    })
  },
  delete(url, param="") {
    return new Promise((resolve,reject) => {
      instance({
        method: 'delete',
        headers: getHeader(),
        url,
        data: param,
      }).then(res => {
        resolve(res);
      }).catch(err =>{
        message.error(err.message)
        reject(err);
      })
    })
  },
}

